<template>
    <div class="default-main">
        <el-row v-loading="state.loading" :gutter="20">
            <el-col class="xs-mb-20" :xs="24" :sm="16">
                <el-form
                    v-if="!state.loading"
                    ref="formRef"
                    @submit.prevent=""
                    @keyup.enter="onSubmit()"
                    :model="state.form"
                    :label-position="'top'"
                    :key="state.formKey"
                >
                    <el-tabs v-model="state.activeTab" type="border-card" :before-leave="onBeforeLeave">
                        <el-tab-pane class="config-tab-pane" v-for="(item, kk) in state.config" :key="kk" :name="item.key" :label="item.title">
                            <FormItem
                                :label="t('title')"
                                prop="title"
                                v-model="state.form[item.key].title"
                                type="string"
                            />

                            <FormItem :label="t('content')" type="editor" prop="content" v-model="state.form[item.key].content" />

                            <!-- 富文本在dialog内全屏编辑器时必须拥有很高的z-index，此处选择单独为editor设定较小的z-index -->
                            <!-- <FormItem
                                :label="item.title"
                                type="editor"
                                @keyup.enter.stop=""
                                @keyup.ctrl.enter="onSubmit()"
                                v-model="state.form[item.key].content"
                                :attr="{}"
                                :input-attr="{}"
                                :key="'content-' + item.id"
                            /> -->
                            <!-- <el-form-item prop="name" :label="t('auth.group.Group name')">
                                <el-input
                                    v-model="state.form.title"
                                    type="string"
                                    :placeholder="t('Please input field', { field: t('auth.group.Group name') })"
                                ></el-input>
                            </el-form-item> -->

                            <!-- <FormItem
                                :label="title"
                                :type="string"
                                v-model="state.form.title"
                                :key="'input-' + item.id"
                            /> -->

                            <!-- <FormItem
                                :label="item.title"
                                :type="string"
                                v-model="state.form[item.name]"
                                :attr="{}"
                                :input-attr="{}"
                                :tip="item.tip"
                                :key="'other-' + item.id"
                            /> -->

                            <!-- 富文本在dialog内全屏编辑器时必须拥有很高的z-index，此处选择单独为editor设定较小的z-index -->
                            <!-- <FormItem
                                v-if="item.type == 'editor'"
                                :label="item.title"
                                :type="item.type"
                                @keyup.enter.stop=""
                                @keyup.ctrl.enter="onSubmit()"
                                v-model="state.form[item.name]"
                                :attr="{ prop: item.name, ...item.extend }"
                                :input-attr="{
                                    style: {
                                        zIndex: 99,
                                    },
                                    ...item.input_extend,
                                }"
                                :tip="item.tip"
                                :key="'editor-' + item.id"
                            /> -->

                            <!-- <FormItem
                                v-else-if="item.type == 'textarea'"
                                :label="item.title"
                                :type="item.type"
                                @keyup.enter.stop=""
                                @keyup.ctrl.enter="onSubmit()"
                                v-model="state.form[item.name]"
                                :attr="{ prop: item.name, ...item.extend }"
                                :input-attr="{ rows: 3, ...item.input_extend }"
                                :tip="item.tip"
                                :key="'textarea-' + item.id"
                            /> -->

                            <!-- <FormItem
                                v-else
                                :label="item.title"
                                :type="item.type"
                                v-model="state.form[item.name]"
                                :attr="{ prop: item.name, ...item.extend }"
                                :input-attr="!isEmpty(item.content) ? { content: item.content, ...item.input_extend } : item.input_extend"
                                :tip="item.tip"
                                :key="'other-' + item.id"
                            /> -->
                            <el-button type="primary" @click="onSubmit()">{{ t('Save') }}</el-button>
                        </el-tab-pane>

                    </el-tabs>
                </el-form>
            </el-col>
        </el-row>

    </div>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'
import { ElMessageBox, ElNotification } from 'element-plus'
import { isEmpty } from 'lodash-es'
import { onActivated, onDeactivated, onMounted, onUnmounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import AddFrom from './add.vue'
import { del, index, postData, postSendTestMail } from '/@/api/backend/routine/config'
import FormItem from '/@/components/formItem/index.vue'
import { adminBaseRoutePath } from '/@/router/static/adminBase'
import type { SiteConfig } from '/@/stores/interface'
import { useSiteConfig } from '/@/stores/siteConfig'
import { uuid } from '/@/utils/random'
import { routePush } from '/@/utils/router'
import { buildValidatorData, type buildValidatorParams } from '/@/utils/validate'
import { closeHotUpdate, openHotUpdate } from '/@/utils/vite'
import createAxios from '/@/utils/axios'

defineOptions({
    name: 'routine/config',
})

const items = reactive({
    editor: '<p>默认内容</p>',
})

const { t } = useI18n()
const siteConfig = useSiteConfig()

const formRef = ref<FormInstance>()

const state: {
    loading: boolean
    config: anyObj
    configGroup: anyObj
    activeTab: string
    showAddForm: boolean
    form: anyObj
    formKey: string
} = reactive({
    loading: true,
    config: [],
    configGroup: {},
    activeTab: '',
    showAddForm: false,
    form: {},
    formKey: uuid(),
})

const getIndex = () => {
    createAxios({
        url: '/backend/site-info/lists',
        method: 'get',
    })
        .then((res) => {
            state.config = res.data
            state.loading = false

            let formNames: anyObj = {}
            for (const key in state.config) {
                state.configGroup[state.config[key].key] = state.config[key].title
                formNames[state.config[key].key] = {title: state.config[key].title, key: state.config[key].key, content:state.config[key].content}
                console.log(key)
                console.log(state.config[key].key)
                console.log(state.config[key].title)
            }

            // 分组
            for (const key in state.configGroup) {
                state.activeTab = key
                break
            }

            state.form = formNames
            state.formKey = uuid()

            console.log('state.form', state.form)
            console.log('state.form.about', state.form.about)
            console.log('state.config', state.config)
            console.log('state.activeTab', state.activeTab)
        })
        .catch(() => {
            state.loading = false
        })
}

const onBeforeLeave = (newTabName: string | number) => {
    if (newTabName == 'add_config') {
        state.showAddForm = true
        return false
    }
}

const onSubmit = () => {
    if (!formRef.value) return
    formRef.value.validate((valid) => {
        if (valid) {
            // 只提交当前tab的表单数据
            const formData: anyObj = {}
            for (const key in state.config) {
                //console.log('提交', state.config[key])
                //console.log('提交', state.activeTab)
                //console.log('提交key', key)
                //console.log('提交key', state.config[key].key)
                if (state.config[key].key != state.activeTab) {
                    continue
                }
                for (const lKey in state.config[key]) {
                    formData[lKey] = state.form[state.activeTab][lKey] ?? ''
                }
            }

            createAxios(
                {
                    url: '/backend/site-info/save',
                    method: 'post',
                    data: formData,
                },
                {
                    showSuccessMessage: true,
                }
            ).then(() => {
                for (const key in siteConfig.$state) {
                    if (formData[key] && siteConfig.$state[key as keyof SiteConfig] != formData[key]) {
                        ;(siteConfig.$state[key as keyof SiteConfig] as any) = formData[key]
                    }
                }
            })
        }
    })
}

onMounted(() => {
    getIndex()
    closeHotUpdate('config')
})
onActivated(() => {
    closeHotUpdate('config')
})
onDeactivated(() => {
    openHotUpdate('config')
})
onUnmounted(() => {
    openHotUpdate('config')
})
</script>

<style scoped lang="scss">
.send-test-mail {
    padding-bottom: 20px;
}
.el-tabs--border-card {
    border: none;
    box-shadow: var(--el-box-shadow-light);
    border-radius: var(--el-border-radius-base);
}
.el-tabs--border-card :deep(.el-tabs__header) {
    background-color: var(--ba-bg-color);
    border-bottom: none;
    border-top-left-radius: var(--el-border-radius-base);
    border-top-right-radius: var(--el-border-radius-base);
}
.el-tabs--border-card :deep(.el-tabs__item.is-active) {
    border: 1px solid transparent;
}
.el-tabs--border-card :deep(.el-tabs__nav-wrap) {
    border-top-left-radius: var(--el-border-radius-base);
    border-top-right-radius: var(--el-border-radius-base);
}
.el-card :deep(.el-card__header) {
    height: 40px;
    padding: 0;
    line-height: 40px;
    border: none;
    padding-left: 20px;
    background-color: var(--ba-bg-color);
}
.config-tab-pane {
    padding: 5px;
}
.config-tab-pane-add {
    width: 80%;
}
.config-form-item {
    display: flex;
    align-items: center;
    .el-form-item {
        flex: 13;
    }
    .config-form-item-name {
        opacity: 0;
        flex: 3;
        font-size: 13px;
        color: var(--el-text-color-disabled);
        padding-left: 20px;
    }
    .del-config-form-item {
        cursor: pointer;
        flex: 1;
        padding-left: 10px;
    }
    .close-icon {
        display: none;
    }
    &:hover {
        .config-form-item-name {
            opacity: 1;
        }
        .close-icon {
            display: block;
            color: var(--el-text-color-disabled) !important;
        }
    }
}
.config_quick_entrance {
    margin-left: 10px;
    margin-bottom: 10px;
}
@media screen and (max-width: 768px) {
    .xs-mb-20 {
        margin-bottom: 20px;
    }
}
</style>
